根據您的要求,我將修改代碼以實現 localStorage 的異步持久化儲存與頁面加載時的數據讀取。所有的代碼修改與注釋均使用英文。
以下是需要修改的三個主要部分:
在此函數中添加異步儲存邏輯,將當前的 historyFEN 轉換為 JSON 並存入 localStorage。
JavaScript
// Locate the saveStateToUndo function and update it as follows:
function saveStateToUndo() {
const state = JSON.stringify(historyFEN);
undoStack.push(state);
if (undoStack.length > 50) undoStack.shift();
redoStack = [];
// Asynchronously save to localStorage
setTimeout(() => {
try {
localStorage.setItem('ejcees_saved_state', state);
} catch (e) {
console.error("Failed to save state to localStorage:", e);
}
}, 0);
}
在頁面加載時,首先嘗試從 localStorage 讀取數據。如果存在有效的數據,則恢復該狀態;否則,使用默認的 INITIAL_FEN 初始化。
JavaScript
// Locate the "// --- Boot the App ---" section at the end of the script:
// 1. Try to load saved state from localStorage
const savedState = localStorage.getItem('ejcees_saved_state');
let initialHistory = null;
if (savedState) {
try {
initialHistory = JSON.parse(savedState);
} catch (e) {
console.error("Failed to parse saved state:", e);
}
}
// 2. Initialize with saved state or default FEN
if (initialHistory && initialHistory.fen) {
historyFEN = initialHistory;
loadFEN(historyFEN.fen);
} else {
loadFEN(INITIAL_FEN);
historyFEN = {
fen: INITIAL_FEN,
move: null,
lastMove: null,
c: "",
v: []
};
}
// 3. Reset UI states based on loaded data
currentBranch = [];
currentStepIndex = 0;
stepSlider.max = 0;
stepSlider.value = 0;
applyLastMoveVisuals(null);
highlightActiveStep(0);
renderRecordUI(); // Ensure the record list is rendered if data was loaded
renderNoteUI();
// 4. Initial save and UI update
saveStateToUndo();
updateToolHighlights();